package net.ikenway.springboot.demo.Controller;

import net.ikenway.springboot.demo.Model.Dto.ResponseBodyDto;
import net.ikenway.springboot.demo.Utils.FileUtil;
import net.ikenway.springboot.demo.Utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MasterKenway <zk@ikenway.net>
 * @Description
 * @date Created Date 12/21/2020
 */
@RestController
@RequestMapping(value = "/api")
public class UploadImageController {
    @Value("${web.upload-path}")
    private String uploadPath;

    @Value("${web.image-path}")
    private String imagePath;

    @RequestMapping(value = "/upload")
    public ResponseBodyDto upload(@RequestParam(value = "file") MultipartFile file) {
        try {
            String fileName = FileUtil.upload(file, Paths.get(".").toAbsolutePath() + uploadPath, file.getOriginalFilename());
            Map<String, String> data = new HashMap<>();
            data.put("url", imagePath + fileName);
            return new ResponseBodyDto(200, "上传成功", data);
        } catch (Exception e) {
            return new ResponseBodyDto(500, e.getMessage());
        }
    }
}
